package base

/*
* @author: hjz
* @time: 2025/4/28 21:07
 */
func spiralOrder(matrix [][]int) []int {
	res := make([]int, 0, len(matrix)*2)
	up, right, down, left := 0, len(matrix[0])-1, len(matrix)-1, 0
	for {
		for i := left; i <= right; i++ { // 上
			res = append(res, matrix[up][i])
		}
		up += 1
		if up > down {
			break
		}
		for i := up; i <= down; i++ { // 右
			res = append(res, matrix[i][right])
		}
		right -= 1
		if right < left {
			break
		}
		for i := right; i >= left; i-- { // 下
			res = append(res, matrix[down][i])
		}
		down -= 1
		if up > down {
			break
		}
		for i := down; i >= up; i-- { // 左
			res = append(res, matrix[i][left])
		}
		left += 1
		if right < left {
			break
		}
	}
	return res
}

// t
func spiralOrder1(matrix [][]int) []int {
	up, right, down, left := 0, len(matrix[0])-1, len(matrix)-1, 0
	res := make([]int, 0, len(matrix)*len(matrix))
	for {
		for i := left; i <= right; i++ { // 上
			res = append(res, matrix[up][i])
		}
		up++
		if up > down {
			break
		}
		for i := up; i <= down; i++ {
			res = append(res, matrix[i][right]) // 右
		}
		right--
		if left > right {
			break
		}
		for i := right; i >= left; i-- {
			res = append(res, matrix[down][i]) //下
		}
		down--
		if up > down {
			break
		}
		for i := down; i >= up; i-- {
			res = append(res, matrix[i][left]) //左
		}
		left++
		if left > right {
			break
		}
	}
	return res
}
